<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="550px" @confirm="handleSubmit" @close="handleClose">
            <el-form class="ls-form" ref="formRef" :rules="rules" :model="formData" label-width="80px" label-position="left">
                <el-form-item label="选择日期" prop="status">
                    <el-date-picker
                        v-model="dateTime"
                        type="daterange"
                        range-separator="~"
                        start-placeholder="Start date"
                        end-placeholder="End date"
                        :size="size"
                        format="YYYY-MM-DD"
                        value-format="x"
                        @change="handleChange"
                        :disabled-date="disabledDate"
                    />
                </el-form-item>
                
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'

import { calendarEdit, calendarAdd } from '@/api/apis'
import Popup from '@/components/popup/index.vue'
import { timeFormat } from '@/utils/util'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑时间段' : '新增时间段'
})
const size = ref<'default' | 'large' | 'small'>('default')
const dateTime = ref([])
const formData = reactive({
    id: '',
    start_time: '' as any,
    end_time: '' as any,
})

const rules = {
    value: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ]
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    if(mode.value == 'add'){
        delete (formData as any).id
    }
    mode.value == 'edit' ? await calendarEdit(formData) : await calendarAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const handleClose = () => {
    emit('close')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (data: Record<any, any>) => {
    console.log(data, 'data')
    if(data.id){
        formData.id = data.id
        formData.start_time = data.start_date
        formData.end_time = data.end_date
    }
    if(data.start_date != '' && data.end_date){
        dateTime.value = [data.start_date, data.end_date] as any // [data.start_date, data.end_date]
    }
}
const handleChange = (e: any) => {
    console.log(e)
    formData.start_time = e[0] / 1000
    formData.end_time = e[1] / 1000
}

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}
defineExpose({
    open,
    setFormData
})
</script>
